const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

// 配置信息
const config = {
    version: '1.0.0',
    packageUrl: 'http://localhost/hotupdate/',
    remoteManifestUrl: 'http://localhost/hotupdate/project.manifest',
    remoteVersionUrl: 'http://localhost/hotupdate/version.manifest',
    assets: {},
    searchPaths: []
};

// 要包含的目录
const includeDirs = [
    path.join(__dirname, '..', 'assets', 'CocosGameFramework', 'scripts', 'game'),
    path.join(__dirname, '..', 'assets', 'CocosGameFramework', 'resources')
];

// 计算文件MD5
function calculateMD5(filePath) {
    const buffer = fs.readFileSync(filePath);
    const hash = crypto.createHash('md5');
    hash.update(buffer);
    return hash.digest('hex');
}

// 递归扫描目录
function scanDirectory(dir, baseDir) {
    const results = {};
    const files = fs.readdirSync(dir);
    
    for (const file of files) {
        const fullPath = path.join(dir, file);
        const relativePath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
        
        if (fs.statSync(fullPath).isDirectory()) {
            Object.assign(results, scanDirectory(fullPath, baseDir));
        } else {
            results[relativePath] = {
                md5: calculateMD5(fullPath),
                size: fs.statSync(fullPath).size
            };
        }
    }
    
    return results;
}

// 扫描所有包含的目录
for (const dir of includeDirs) {
    if (fs.existsSync(dir)) {
        const baseDir = path.join(__dirname, '..');
        Object.assign(config.assets, scanDirectory(dir, baseDir));
    }
}

// 生成 project.manifest
const projectManifest = JSON.stringify(config, null, 2);
fs.writeFileSync(path.join(__dirname, 'project.manifest'), projectManifest);

// 生成 version.manifest (只包含版本信息)
const versionConfig = {
    version: config.version,
    packageUrl: config.packageUrl,
    remoteManifestUrl: config.remoteManifestUrl,
    remoteVersionUrl: config.remoteVersionUrl
};
const versionManifest = JSON.stringify(versionConfig, null, 2);
fs.writeFileSync(path.join(__dirname, 'version.manifest'), versionManifest);

console.log('Manifest files generated successfully!');